import Banner from "./Banner";
import EnemyController from "./EnemyController";
import { AStarManager, AStarNode, AStar_Node_Type } from "./Framework/Algorithm/AStar";
import { Constant, ItemType, SuppliesType } from "./Framework/Const/Constant";
import { DataManager } from "./Framework/Managers/DataManager";
import { PoolManager } from "./Framework/Managers/PoolManager";
import { UIManager } from "./Framework/Managers/UIManager";
import RedDot from "./Framework/UI/RedDot";
import NodeUtil from "./Framework/Utils/NodeUtil";
import { ResourceUtil } from "./Framework/Utils/ResourceUtil";
import { ZTool } from "./Framework/Utils/ZTool";
import PlayerController from "./PlayerController";

const { ccclass, property } = cc._decorator;

export enum GameMode {
    ESCAPE,
    TEAM
}

@ccclass
export default class GameManager extends cc.Component {
    public static Instance: GameManager = null;
    static IsFirstUnlock = true;
    static IsGameOver: boolean = false;

    @property(cc.Node)
    playerNd: cc.Node = null;

    @property(cc.Node)
    ItemsNd: cc.Node = null;

    player: cc.Node = null;
    playerCtrl: PlayerController = null;

    static GameMode: GameMode = GameMode.ESCAPE;

    onLoad() {
        GameManager.Instance = this;

        cc.director.getPhysicsManager().enabled = true;
        // cc.director.getPhysicsManager().enabledAccumulator = true;
        cc.director.getPhysicsManager().debugDrawFlags = 0;

        this.InitPlayer();
        this.InitMap();

        if (GameManager.GameMode == GameMode.ESCAPE) {
            UIManager.Instance.ShowPanel(Constant.Panel.CommonTipPanel, ["搜寻物资并找到撤离点。", "知道了", ``, () => {
                UIManager.Instance.HidePanel(Constant.Panel.CommonTipPanel);
            }]);
        } else {
            if (Banner.NeedShowMoreAd) {
                Banner.Instance.ShowVideoAd(() => { });
            }
        }
    }

    //#region 地图

    @property(cc.TiledMap)
    tiledMap: cc.TiledMap = null;

    @property(cc.Node)
    MapNodes: cc.Node = null;

    map: Map<string, cc.Node> = new Map<string, cc.Node>();
    aStarMap: Map<string, cc.Node> = new Map<string, cc.Node>();//标记为障碍物的节点

    timer: number = 0;

    // @property({ type: [cc.Node] })
    // RedTeam: cc.Node[] = [];

    // @property({ type: [cc.Node] })
    // BuleTeam: cc.Node[] = [];

    InitPlayer() {
        ResourceUtil.LoadPrefab(`Player`).then((prefab: cc.Prefab) => {
            if (this.player) this.player.destroy();
            this.player = cc.instantiate(prefab);
            this.player.setParent(cc.find("Canvas"));
            this.player.setSiblingIndex(this.playerNd.getSiblingIndex());
            NodeUtil.SetWorldPositionToOtherNode(this.player, this.playerNd);
            this.playerCtrl = this.player.getComponent(PlayerController);
        })
    }

    InitMap() {
        // AStarManager.Instance.InitMapInfo(this.tiledMap.getLayer(`Background`).getLayerSize().width, this.tiledMap.getLayer(`Background`).getLayerSize().height);

        let tiledSize = this.tiledMap.getTileSize();//每个格子的大小

        //碰撞层 - 用于主角与地图的碰撞
        let layer = this.tiledMap.getLayer(`Obstacle`);
        for (let i = 0; i < layer.getLayerSize().width; i++) {
            for (let j = 0; j < layer.getLayerSize().height; j++) {
                let tiled = layer.getTiledTileAt(i, j, true);
                if (tiled.gid != 0) {
                    tiled.node.group = `Obstacle`;
                    let body = tiled.node.addComponent(cc.RigidBody);
                    body.type = cc.RigidBodyType.Static;
                    let collider = tiled.node.addComponent(cc.PhysicsBoxCollider);
                    tiled.node.setContentSize(tiledSize.width, tiledSize.height);
                    collider.offset = cc.v2(tiledSize.width / 2, tiledSize.height / 2);
                    collider.size = tiledSize;
                    collider.apply();
                }
            }
        }

        // //Astar 寻路层 - 用于敌人寻路（要比碰撞层大一圈）
        // layer = this.tiledMap.getLayer(`AStar`);
        // for (let i = 0; i < layer.getLayerSize().width; i++) {
        //     for (let j = 0; j < layer.getLayerSize().height; j++) {
        //         let tiled = layer.getTiledTileAt(i, j, true);
        //         AStarManager.Instance.SetMap(i, j, tiled.gid != 0 ? AStar_Node_Type.Obstacle : AStar_Node_Type.Normal);
        //         let node = new cc.Node();
        //         node.setParent(this.MapNodes);
        //         node.setContentSize(tiledSize.width * this.tiledMap.node.scaleX, tiledSize.height * this.tiledMap.node.scaleX);
        //         NodeUtil.SetWorldPosition(node, NodeUtil.GetWorldPosition(tiled.node));
        //         node.setPosition(node.position.x + tiledSize.width / 2 * this.tiledMap.node.scaleX, node.position.y + tiledSize.height / 2 * this.tiledMap.node.scaleY);
        //         this.map.set(`${i}_${j}`, node);

        //         if (tiled.gid != 0) { this.aStarMap.set(`${i}_${j}`, node); }
        //     }
        // }
    }

    protected update(dt: number): void {
        this.timer += dt;
    }

    GetMapPosition(node: cc.Node): string {
        const result = Array.from(this.map.entries()).find(([k, v]) => {
            return v.getBoundingBoxToWorld().contains(NodeUtil.GetWorldPosition(node));
        });
        if (result) return result[0];
        return "";
    }

    //玩家在标记为障碍物的位置时不寻路
    IsInCantArrivePosition(node: cc.Node): boolean {
        const result = Array.from(this.aStarMap.entries()).find(([k, v]) => {
            return v.getBoundingBoxToWorld().contains(NodeUtil.GetWorldPosition(node));
        });

        if (result) {
            return true;
        }

        return false;
    }


    //#endregion

}